<?php

namespace app\api\controller\v1;

use app\common\controller\Api;
use think\Request;
use think\config;
use app\common\logic\PayLogic;
use app\common\logic\OrderLogic;
use app\common\model\Order;
use app\common\model\UnifiedOrder;
use app\common\model\Pay as PayModel;
class Pay extends Api
{
    protected $authenticate=null;

    
    public function index(){
        $rule = [
            'out_trade_no|公共订单号'=>'require',
            'channel|支付渠道'=>'require'
        ];
        
        $this->validate($params = paramForm(),$rule);
        
        if($params['channel']&&!isset($params['openid'])){
            error('公众号内下单需要需要openid参数');
        }
        
        $logic = new PayLogic();
        //混合订单价格,如果有子订单已经支付了，则提示用户需要在个人中心-》订单中心分开支付
        $mixinRT = $logic->mixinOrder($params['out_trade_no']);

        if(!$mixinRT['code']){
            error($mixinRT['msg']);
        }
        $allAmount = $mixinRT['data'];
        $pay =[
            'channel'=>$params['channel'],
            'body'=>'来自合并订单'.$params['out_trade_no'].'的支付',
            'total_fee'=>$allAmount,
            'out_trade_no'=>$params['out_trade_no'],
            'open_id'=>isset($params['openid'])?$params['openid']:null
        ];
        $preOrderRT = $logic->unifiedpay($pay);
       
        if(!$preOrderRT['code']){
            error($preOrderRT['msg']);
        }
        
        success($preOrderRT['data']);
        
    }
    
    /**
     * @desc 重新发起支付
     * @param open_id 用户的opne_id,在channel为wx_pub时必选
     * @param trade_no 订单序列号
     * @param channel 支付渠道
     * @throws \think\exception\DbException
     */
    public function again(){
        $params = paramForm();
        $rule = [
            'trade_no|订单序列必填'=>'require'
        ];
        $this->validate($params,$rule);
        
        $logic = new PayLogic();
        $order = Order::get(['trade_no'=>$params['trade_no']]);
        $unifiedOrder = UnifiedOrder::get(['order_id'=>$order->id]);
        $new_out_trade_no = 'no_'.OrderLogic::createUuid();
    
        //没必要管这个记录啊？？
        //需要先替换支付记录表里面的
//        $payInfo = PayModel::get(['out_trade_no'=>$unifiedOrder->out_trade_no]);
//        var_dump($unifiedOrder->out_trade_no,$payInfo);
//        $payInfo->out_trade_no = $new_out_trade_no;
//        $payInfo->isUpdate()->save();
        //替换同一订单表里面的
        $unifiedOrder->out_trade_no = $new_out_trade_no;
        $unifiedOrder->isUpdate()->save();
        
        
        $pay =[
            'channel'=>$params['channel'],
            'body'=>'来自单个订单'.$order->id.'的重新发起支付',
            'total_fee'=>$order->amount,
            'out_trade_no'=>$new_out_trade_no,//确保是新的订单号，不会重复
            'open_id'=>isset($params['openid'])?$params['openid']:null
        ];
        $preOrderRT = $logic->unifiedpay($pay);
    
        if(!$preOrderRT['code']){
            error($preOrderRT['msg']);
        }
    
        success($preOrderRT['data']);
        
    }
    
    
    

}
